package com.ljy.farm.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ljy.farm.datasource.entities.Functions;
import com.ljy.farm.datasource.entities.User;
import com.ljy.farm.datasource.entities.UserBusiness;
import com.ljy.farm.service.functions.FunctionsService;
import com.ljy.farm.utils.BaseResponseInfo;
import com.ljy.farm.constants.ExceptionConstants;
import com.ljy.farm.exception.BusinessRunTimeException;
import com.ljy.farm.service.userBusiness.UserBusinessService;
import com.ljy.farm.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping(value = "/functions")
public class FunctionsController {
    private Logger logger = LoggerFactory.getLogger(FunctionsController.class);

    @Resource
    private FunctionsService functionsService;

    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private UserService userService;

    @PostMapping(value = "/findMenu")
    public JSONArray findMenu(@RequestParam(value = "pNumber") String pNumber,
                              @RequestParam(value = "hasFunctions") String hasFunctions,
                              HttpServletRequest request) throws Exception {
        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        try {
            //当前用户所拥有的功能列表，格式如：[1][2][5]
            String fc = hasFunctions;
            List<Functions> dataList = functionsService.getRoleFunctions(pNumber);
            if (dataList.size() != 0) {
                // 获取当前用户信息
                User currentUser = userService.getCurrentUser();
                if (currentUser != null) {
                    // 根据用户角色过滤功能模块
                    dataList = filterFunctionsByUserRole(dataList, currentUser);
                }
                dataArray = getMenuByFunction(dataList, fc);
            }
        } catch (DataAccessException e) {
            logger.error(">>>>>>>>>>>>>>>>>>>查找异常", e);
        }
        return dataArray;
    }

    /**
     * 根据用户角色过滤功能模块
     * @param dataList 原始功能列表
     * @param currentUser 当前用户
     * @return 过滤后的功能列表
     */
    private List<Functions> filterFunctionsByUserRole(List<Functions> dataList, User currentUser) throws Exception {
        List<Functions> filteredList = new ArrayList<>();
        
        // 获取用户角色信息
        List<UserBusiness> userRoles = userBusinessService.findRoleByUserId(currentUser.getId().toString());
        String userRoleName = "";
        
        // 添加调试日志
        logger.info("当前用户ID: {}, 用户名: {}, 登录名: {}", currentUser.getId(), currentUser.getUsername(), currentUser.getLoginName());
        
        if (userRoles != null && !userRoles.isEmpty()) {
            // 获取第一个角色名称
            String roleIds = userRoles.get(0).getValue();
            logger.info("用户角色信息: {}", roleIds);
            
            if (roleIds != null && !roleIds.isEmpty()) {
                // 解析角色ID，格式如：[1][2]
                String[] roleIdArray = roleIds.replace("[", "").replace("]", "").split("\\]\\[");
                if (roleIdArray.length > 0) {
                    Long roleId = Long.parseLong(roleIdArray[0]);
                    userRoleName = roleId.toString();
                    logger.info("解析后的角色ID: {}", userRoleName);
                }
            }
        } else {
            logger.warn("未找到用户角色信息");
        }
        
        // 根据角色ID进行判断
        boolean isFinanceManager = "25".equals(userRoleName);
        boolean isTenant = "10".equals(userRoleName);
        
        logger.info("角色判断结果 - 财务管理员: {}, 租户: {}", isFinanceManager, isTenant);
        
        for (Functions function : dataList) {
            boolean shouldInclude = true;
            
            if (isFinanceManager) {
                // 财务管理员（角色ID=25）显示：财务管理、报表查询、基本资料
                shouldInclude = "财务管理".equals(function.getName()) ||
                               "报表查询".equals(function.getName()) ||
                               "基本资料".equals(function.getName());
                if (shouldInclude) {
                    logger.info("财务管理员功能: {}", function.getName());
                }
            } else if (isTenant) {
                // 租户（角色ID=10）显示：零售管理、采购管理、销售管理、物资管理、仓库管理
                shouldInclude = "零售管理".equals(function.getName()) ||
                               "采购管理".equals(function.getName()) ||
                               "销售管理".equals(function.getName()) ||
                               "物资管理".equals(function.getName()) ||
                               "仓库管理".equals(function.getName());
                if (shouldInclude) {
                    logger.info("租户功能: {}", function.getName());
                }
            } else {
                // 其他身份不修改，显示所有功能
                shouldInclude = true;
                logger.info("其他身份功能: {}", function.getName());
            }
            
            if (shouldInclude) {
                filteredList.add(function);
            }
        }
        
        logger.info("过滤后的功能模块数量: {}", filteredList.size());
        return filteredList;
    }

    public JSONArray getMenuByFunction(List<Functions> dataList, String fc) throws Exception {
        JSONArray dataArray = new JSONArray();
        logger.info("getMenuByFunction - 输入功能列表数量: {}, functions字符串: {}", dataList.size(), fc);
        
        for (Functions functions : dataList) {
            JSONObject item = new JSONObject();
            List<Functions> newList = functionsService.getRoleFunctions(functions.getNumber());
            item.put("id", functions.getId());
            item.put("text", functions.getName());
            item.put("icon", functions.getIcon());
            
            logger.info("处理功能模块: ID={}, 名称={}, 子菜单数量={}", functions.getId(), functions.getName(), newList.size());
            
            if (newList.size() > 0) {
                // 有子菜单的情况
                JSONArray childrenArr = getMenuByFunction(newList, fc);
                logger.info("功能模块 {} 的子菜单过滤后数量: {}", functions.getName(), childrenArr.size());
                
                // 修改逻辑：即使子菜单为空，也要添加父菜单（如果父菜单在functions字符串中）
                if (childrenArr.size() > 0) {
                    item.put("children", childrenArr);
                    dataArray.add(item);
                    logger.info("添加有子菜单的功能模块: {}", functions.getName());
                } else if (fc.indexOf("[" + functions.getId().toString() + "]") != -1) {
                    // 如果父菜单在functions字符串中，即使没有子菜单也要添加
                    dataArray.add(item);
                    logger.info("添加父菜单（无子菜单但有权限）: {}", functions.getName());
                }
            } else {
                // 没有子菜单的情况
                item.put("url", functions.getUrl());
                if (fc.indexOf("[" + functions.getId().toString() + "]") != -1) {
                    dataArray.add(item);
                    logger.info("添加叶子功能模块: {}", functions.getName());
                }
            }
        }
        
        logger.info("getMenuByFunction - 返回菜单数量: {}", dataArray.size());
        return dataArray;
    }

    /**
     * 角色对应功能显示
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/findRoleFunctions")
    public JSONArray findRoleFunctions(@RequestParam("UBType") String type, @RequestParam("UBKeyId") String keyId,
                                       HttpServletRequest request) throws Exception {
        JSONArray arr = new JSONArray();
        try {
            List<Functions> dataListFun = functionsService.findRoleFunctions("0");
            //开始拼接json数据
            JSONObject outer = new JSONObject();
            outer.put("id", 1);
            outer.put("text", "功能列表");
            outer.put("state", "open");
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataListFun) {
                //根据条件从列表里面移除"系统管理"
                List<Functions> dataList = new ArrayList<Functions>();
                for (Functions fun : dataListFun) {
                    //从session中获取租户id
                    String loginName = null;
                    Object userInfo = request.getSession().getAttribute("user");
                    if (userInfo != null) {
                        User user = (User) userInfo;
                        loginName = user.getLoginName();
                    }
                    if (("admin").equals(loginName)) {
                        dataList.add(fun);
                    } else {
                        if (!("系统管理").equals(fun.getName())) {
                            dataList.add(fun);
                        }
                    }
                }
                dataArray = getFunctionList(dataList, type, keyId);
                outer.put("children", dataArray);
            }
            arr.add(outer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }

    public JSONArray getFunctionList(List<Functions> dataList, String type, String keyId) throws Exception {
        JSONArray dataArray = new JSONArray();
        if (null != dataList) {
            for (Functions functions : dataList) {
                JSONObject item = new JSONObject();
                item.put("id", functions.getId());
                item.put("text", functions.getName());
                Boolean flag = false;
                try {
                    flag = userBusinessService.checkIsUserBusinessExist(type, keyId, "[" + functions.getId().toString() + "]");
                } catch (Exception e) {
                    logger.error(">>>>>>>>>>>>>>>>>设置角色对应的功能：类型" + type + " KeyId为： " + keyId + " 存在异常！");
                }
                if (flag == true) {
                    item.put("checked", true);
                }
                List<Functions> funList = functionsService.findRoleFunctions(functions.getNumber());
                if (funList.size() > 0) {
                    JSONArray funArr = getFunctionList(funList, type, keyId);
                    item.put("children", funArr);
                    dataArray.add(item);
                } else {
                    dataArray.add(item);
                }
            }
        }
        return dataArray;
    }

    /**
     * 根据id列表查找功能信息
     *
     * @param functionsIds
     * @param request
     * @return
     */
    @GetMapping(value = "/findByIds")
    public BaseResponseInfo findByIds(@RequestParam("functionsIds") String functionsIds,
                                      HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            List<Functions> dataList = functionsService.findByIds(functionsIds);
            JSONObject outer = new JSONObject();
            outer.put("total", dataList.size());
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (Functions functions : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("Id", functions.getId());
                    item.put("Name", functions.getName());
                    item.put("PushBtn", functions.getPushbtn());
                    item.put("op", 1);
                    dataArray.add(item);
                }
            }
            outer.put("rows", dataArray);
            res.code = 200;
            res.data = outer;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    /**
     * create by: qiankunpingtai
     * website：https://qiankunpingtai.cn
     * description:
     * 批量删除功能模块信息
     * create time: 2019/3/29 11:15
     *
     * @return java.lang.Object
     * @Param: ids
     */
    @RequestMapping(value = "/batchDeleteFunctionsByIds")
    public Object batchDeleteFunctionsByIds(@RequestParam("ids") String ids) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        // 获取当前用户信息并传递给FunctionsService
        User currentUser = userService.getCurrentUser();
        int i = functionsService.batchDeleteFunctionsByIds(ids, currentUser);
        if (i < 1) {
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                    ExceptionConstants.FUNCTIONS_DELETE_FAILED_CODE, ExceptionConstants.FUNCTIONS_DELETE_FAILED_MSG, ids);
            throw new BusinessRunTimeException(ExceptionConstants.FUNCTIONS_DELETE_FAILED_CODE,
                    ExceptionConstants.FUNCTIONS_DELETE_FAILED_MSG);
        }
        return result;
    }
}
